package com.chwn.curiousdiary.adapter;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.chwn.curiousdiary.DiaryApplication;
import com.chwn.curiousdiary.R;
import com.chwn.curiousdiary.api.IUserApi;
import com.chwn.curiousdiary.api.NetWork;
import com.chwn.curiousdiary.bean.StoryBean;
import com.chwn.curiousdiary.bean.StoryListBean;
import com.chwn.curiousdiary.download.DownHelper;
import com.chwn.curiousdiary.gloable.Constant;
import com.chwn.curiousdiary.gloable.CustomEvent;
import com.chwn.curiousdiary.gloable.UserUtils;
import com.chwn.curiousdiary.utils.PopupWindowUtils;
import com.chwn.harulib.adapter.base.CommonBaseAdapter;
import com.chwn.harulib.mvp.rx.HttpResult;

import java.util.List;

import de.greenrobot.event.EventBus;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Myshikin on 2017/7/17.
 *
 */

public abstract class AStoryAdapter<T> extends CommonBaseAdapter<T> {

    private boolean   down;
    private ImageView collectView;
    private int       stroyCollectionState;

    public AStoryAdapter(Context context, List<T> datas, boolean isOpenLoadMore) {
        super(context, datas, isOpenLoadMore);
    }


    protected void showPopup(View view, StoryBean bean) {
        storyBean = bean;
        showPopupTwo(view);
    }

    protected void showPopup(View view, StoryListBean bean) {
        storyListBean = bean;
        showPopupTwo(view);
    }

    private PopupWindow mPopWindow;
    private int mWidth;

    void showPopupTwo(View view) {
        down = false;



        View contentView = LayoutInflater.from(mContext).inflate(R.layout.layout_more, null);
        mPopWindow = new PopupWindow(contentView,
                RecyclerView.LayoutParams.WRAP_CONTENT, RecyclerView.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(contentView);

        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        LinearLayout mLLBG = (LinearLayout) contentView.findViewById(R.id.ll_bg);
        mLLBG.measure(w, h);
        mWidth = mLLBG.getMeasuredWidth();//获取测量宽度px

        ImageView downView = (ImageView) contentView.findViewById(R.id.iv_more_down);
        if (!TextUtils.isEmpty(DiaryApplication.mInstance.getUserToken())) {
            down = DownHelper.isDown(mContext, getStoryId());
        }

        mPopWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopWindow.setOutsideTouchable(true);

        downView.setImageResource(down ? R.drawable.icon_downed_more : R.drawable.icon_down_more);
        downView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                download();
            }
        });

        contentView.findViewById(R.id.iv_more_share).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                share();
            }
        });

        collectView = (ImageView) contentView.findViewById(R.id.iv_more_collect);
        stroyCollectionState = getStroyCollectionState();
        collectView.setImageResource(stroyCollectionState == 0 ? R.drawable.icon_collect_more : R.drawable.icon_collected_more);
        collectView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                collect();
            }
        });

        mPopWindow.setOutsideTouchable(true);

        mPopWindow.setAnimationStyle(PopupWindowUtils.ANIMATION_RIGHT);
        int width = view.getWidth();
        mPopWindow.showAsDropDown(view, -400, 10);

    }

    protected abstract void collect();

    protected abstract void download();

    protected abstract void share();


    protected void downLoad(StoryBean data) {
        mPopWindow.dismiss();
        if (!UserUtils.isLogin(mContext)) {
            return;
        }
        if (data.getDownState() == 0 && !down) {
            DownHelper.downStory(mContext, data);
            data.setDownState(1);
        }

    }

    protected void downLoad(StoryListBean data) {
        mPopWindow.dismiss();
        if (!UserUtils.isLogin(mContext)) {
            return;
        }
        data.getStroyCollectionState();
        if (data.getDownState() == 0) {
            StoryBean storyBean = new StoryBean(data);
            DownHelper.downStory(mContext, storyBean);
            data.setDownState(1);
        }

    }

    private StoryBean     storyBean;
    private StoryListBean storyListBean;

    protected void collect(StoryBean data) {
        String userToken = checkData();

        if (TextUtils.isEmpty(userToken)) {
            mPopWindow.dismiss();
            return;
        }


        NetWork.getInstance().getApiService(IUserApi.class)
                .collectionStory(data.getStoryId(), userToken, Constant.OSTYPE, stroyCollectionState == 1 ? 0 : 1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<HttpResult<Object>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(mContext, getStroyCollectionState() == 0 ? "收藏失败" : "取消收藏失败", Toast.LENGTH_SHORT).show();
                        mPopWindow.dismiss();
                    }

                    @Override
                    public void onNext(HttpResult<Object> objectHttpResult) {
                        stroyCollectionState = stroyCollectionState == 1 ? 0 : 1;
                        upDateStroyCollectionState(stroyCollectionState);
                        collectView.setImageResource(stroyCollectionState == 0 ? R.drawable.icon_collect_more : R.drawable.icon_collected_more);
                        Toast.makeText(mContext, stroyCollectionState == 1 ? "收藏成功" : "取消收藏成功", Toast.LENGTH_SHORT).show();
                        collectView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mPopWindow.dismiss();
                            }
                        } , 300);
                    }
                });
    }

    protected void upDateStroyCollectionState(int state) {
        if (storyBean != null) {
            storyBean.setStroyCollectionState(state);
        }

        if (storyListBean != null) {
            storyListBean.setStroyCollectionState(state);
        }

        CustomEvent customEvent = new CustomEvent(CustomEvent.UPDATE_COLLECT, state);
        customEvent.setMessage(getStoryId());
        EventBus.getDefault().post(customEvent);

    }

    protected void collect(StoryListBean data) {
        String userToken = checkData();

        if (TextUtils.isEmpty(userToken)) {
            mPopWindow.dismiss();
            return;
        }


        NetWork.getInstance().getApiService(IUserApi.class)
                .collectionStory(data.getStoryId(), userToken, Constant.OSTYPE, stroyCollectionState == 1 ? 0 : 1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<HttpResult<Object>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(mContext, stroyCollectionState == 0 ? "收藏失败" : "取消收藏失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(HttpResult<Object> objectHttpResult) {
                        stroyCollectionState = stroyCollectionState == 1 ? 0 : 1;
                        upDateStroyCollectionState(stroyCollectionState);
                        collectView.setImageResource(stroyCollectionState == 0 ? R.drawable.icon_collect_more : R.drawable.icon_collected_more);
                        Toast.makeText(mContext, stroyCollectionState == 1 ? "收藏成功" : "取消收藏成功", Toast.LENGTH_SHORT).show();
                        collectView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mPopWindow.dismiss();
                            }
                        } , 300);
                    }
                });
    }

    private String checkData() {
        if (!UserUtils.isLogin(mContext)) {
            return "";
        }
        return DiaryApplication.mInstance.getUserToken();
    }

    protected void share(StoryBean data) {
        CustomEvent customEvent = new CustomEvent(CustomEvent.SHARE_STORY);
        customEvent.setMessage(data);
        EventBus.getDefault().post(customEvent);
        mPopWindow.dismiss();
    }

    protected void share(StoryListBean data) {
        CustomEvent customEvent = new CustomEvent(CustomEvent.SHARE_STORY);
        customEvent.setMessage(data);
        EventBus.getDefault().post(customEvent);
        mPopWindow.dismiss();
    }

    private String getStoryId() {
        if (storyBean != null) {
            return storyBean.getStoryId();
        }
        if (storyListBean != null) {
            return storyListBean.getStoryId();
        }
        return "";
    }

    private int getStroyCollectionState() {
        if (storyBean != null) {
            return storyBean.getStroyCollectionState();
        }
        if (storyListBean != null) {
            return storyListBean.getStroyCollectionState();
        }
        return 0;
    }
}
